<template>
  <div class="pos-rlt">
    <div class="mask" v-if="loading">
      <div class="wfull flx-c" style="margin-top:5%;">
        <div style="background:#333;color:#fff;border-radius:30px;padding:10px 45px;">
          <a-spin size="large" class="mr15" />AI小助手正在处理过程中，请您耐心等待...
        </div>
      </div>
    </div>
    <div v-if="!showHelper" class="helper" @click="showHelper=true">
      <a-icon type="android" class="fs24 white"/>
    </div>
    <ZgDrawer
      width="15%"
      v-model="showMenuDrawer">
      <div class="wfull scroll pr10" :style="{height:`${winHeight-50}px`}">
        <a-collapse accordion>
          <a-collapse-panel v-for="menu in menuArr" :key="menu.id">
            <div slot="header">
              <a-icon v-if="menu.icon&&menu.icon.length>0" :type="menu.icon" class="mr10"/>
              {{ menu.name }}
            </div>
            <a-button
              class="mr10 mb10"
              v-for="c in menu.children"
              :key="c.id"
              @click="toPage(`/${menu.code}/${c.code}`)">
              {{ c.name }}
            </a-button>
          </a-collapse-panel>
        </a-collapse>
      </div>
    </ZgDrawer>
    <ChangePwd ref="pwdModal"></ChangePwd>
    <div class="wfull h60 flx-b pl30 pr30" style="background: #40a9ff;box-shadow: 0 5px 10px -4px rgba(0, 0, 0, 0.3);">
      <div class="fw8 fs20 white flx-s">
        <div class="mr10"><ZgImgHolder :width="40" :height="40" :src="sysLogo"></ZgImgHolder></div>
        <div class="cpt" @click="toHome">{{ sysName }}</div>
      </div>
      <div class="flx-e">
        <!--
        <span @click="sendOrder">发送消息</span>
        <span class="mr10 white cpt" @click="showContext">查看参数</span>
        -->
        <span class="mr30 white cpt" @click="passUserInfo">{{ currTime }}</span>
        <a-tooltip title="刷新">
          <div class="btn flx-c mr10" @click="refresh()">
            <i class="fa fa-refresh white"/>
          </div>
        </a-tooltip>
        <a-tooltip title="全屏">
          <div class="btn flx-c mr10" @click="toScreenFull()">
            <i class="fa fa-arrows-alt white" />
          </div>
        </a-tooltip>
        <a-tooltip title="菜单">
          <div class="btn flx-c mr10" @click="openMenuDrawer()">
            <i class="fa fa-th-list white" />
          </div>
        </a-tooltip>
        <a-tooltip v-if="wsConnected" title="二维码">
          <a-popover v-model="showQrCode" trigger="click">
            <div slot="content">
              <img :src="qrCodeUrl" class="w200 h200/">
            </div>
            <div class="btn flx-c mr10">
              <i class="fa fa-qrcode white" />
            </div>
          </a-popover>
        </a-tooltip>
        <a-tooltip title="小助手">
          <div class="btn flx-c mr45" @click="toggleHelper()">
            <i class="fa fa-user-circle-o white" />
          </div>
        </a-tooltip>
        <a-dropdown placement="bottomRight">
          <div>
            <a-avatar :src="currentUser.avatar" class="mr10"/>
            <span class="white">{{ currentUser.name }}</span>
          </div>
          <template v-slot:overlay>
            <a-menu class="ant-pro-drop-down menu" :selected-keys="[]">
              <a-menu-item key="settings" @click="toSettings">
                <a-icon type="setting" />
                个人设置
              </a-menu-item>
              <a-menu-item key="pwd" @click="toChangPwd">
                <a-icon type="lock" />
                修改密码
              </a-menu-item>
              <a-menu-divider/>
              <a-menu-item key="logout" @click="handleLogout">
                <a-icon type="logout" />
                退出登录
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </div>
    <a-row>
      <a-col :span="24-rightWidth">
        <div class="wfull content pd10 scroll" :style="{height:`${winHeight-60}px`}">
          <router-view v-if="isRouterActive"/>
        </div>
      </a-col>
      <a-col :span="rightWidth">
        <div
          class="wfull flx-c scroll"
          style="background:#cee9fe;"
          :style="{height:`${winHeight-60}px`}">
          <iframe
            ref="iframe"
            :src="src"
            frameborder="0"
            scrolling="no"
            @load="passUserInfo"
            class="zg-iframe">
          </iframe>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import screenfull from 'screenfull'
import { Modal } from 'ant-design-vue'
import ChangePwd from '@/views/account/personal/ChangePwd'
import { v4 as uuidv4 } from 'uuid'
import { encrypt } from '@/utils/rsa'
const uuid = uuidv4().replace(/-/g, '')
localStorage.setItem('uuid', uuid)
let handler = null
export default {
  components: {
    ChangePwd
  },
  data () {
    return {
      sysLogo: '',
      sysName: '',
      loading: false,
      currTime: '',
      showHelper: true,
      showQrCode: false,
      isRouterActive: true,
      showMenuDrawer: false,
      qrCodeUrl: '',
      menuArr: [],
      wsHandler: null,
      wsConnected: false,
      src: 'http://172.16.150.213:39800/chatBI-web/assistant'
      // src: 'http://172.16.39.221:8100/#/pages/index/test'
    }
  },
  mounted () {
    this.ssoLogin()
    if (handler === null) {
      handler = setInterval(() => {
        this.ssoCheck()
      }, 600000)
    }
    this.findConfig('sysName', data => {
      this.sysName = data && data.content ? data.content : ''
    })
    this.findConfig('sysLogo', data => {
      this.sysLogo = data && data.content ? data.content : ''
    })
    // 结算页面接收小助手（iframe页面）发送来的消息
    window.onmessage = (event) => {
      const msg = event.data
      console.log('msg', msg)
      if (typeof msg === 'object') {
        if (msg.source === 'helper') {
          if (msg.type === 'preSend') {
            this.sendMsg({
              type: 'send',
              data: Object.assign(
                this.$store.state.assembleJson.context,
                { order: msg.words }
              )
            })
          } else {
            alert(JSON.stringify(msg))
          }
        }
      }
    }

    setInterval(() => {
      this.generateTime()
    }, 1000)
    this.fetchMenu()
  },
  created () {
    this.connWebSocket()
    this.$eventBus.$off('homeSendText')
    this.$eventBus.$on('homeSendText', (text) => {
      this.sendMsg({
        type: 'send',
        data: Object.assign(
          this.$store.state.assembleJson.context,
          { order: text }
        )
      })
    })
  },
  beforeDestroy () {
    if (this.wsHandler) {
      // 关闭WebSocket连接
      this.wsHandler.close()
    }
  },
  computed: {
    rightWidth () {
      return this.showHelper ? 5 : 0
    }
  },
  methods: {
    ssoLogin () {
      const username = 'zhangt'
      const password = 'Aa123456789#'
      this.$http.post('/zg-system/un/sso', {
        username: username,
        passwd: encodeURIComponent(encrypt(password)),
        system: 'jiesuan_in'
      }, casToken => {
        localStorage.setItem('casToken', casToken)
      }, (res) => {
        console.log('登录统一认证异常', res)
      })
    },
    ssoCheck () {
      this.$http.post('/zg-system/un/sso', {
        ssoToken: localStorage.getItem('casToken')
      }, () => {
        console.log('统一认证Token正常续期')
      }, (res) => {
        console.log('统一认证Token续期异常', res)
      })
    },
    sendOrder () {
      const flag = this.$store.state.assembleJson.flag
      this.$eventBus.$emit('order', { flag: flag, order: '123' })
    },
    showContext () {
      const assembleJson = this.$store.state.assembleJson
      alert(JSON.stringify(assembleJson))
    },
    // 处理小助手的指令
    handleHelperOrder (result) {
      const json = JSON.parse(result)
      console.log('result', json)

      if (json.order === 'page') {
        // 跳转页面
        if (json.page === 'openTodoPage') {
          this.toPage('/flowHandle/todoList')
        } else if (json.page === 'openColumnPage') {
          this.toPage('/autoform/column')
        } else if (json.page === 'openStartPage') {
          this.toPage('/flowHandle/startFlow')
        } else if (json.page === 'openCompletePage') {
          // 已办结
          // this.toPage('/flowHandle/completeFlow')
        } else if (json.page === 'openCancelPage') {
          // 已作废
        } else if (json.page === 'openNextPage') {
          // 后续流程
        } else if (json.page === 'openDraftPage') {
          //  草稿箱
        } else if (json.page === 'openInProgressPage') {
          //  进行中
        } else if (json.page === 'openViewPage') {
          // 视图管理
          this.toPage('/autoform/view')
        }
      } else if (json.order === 'dataList') {
        const flag = this.$store.state.assembleJson.flag
        this.$eventBus.$emit('order', Object.assign({ flag: flag }, json))
      }
    },
    connWebSocket () {
      const that = this
      const username = this.$store.state.user.username
      const str = `pc-${uuid}-${username}`
      console.log('xxxxxxxx', str)
      if ('WebSocket' in window) {
        // 打开一个 web socket
        that.wsHandler = new WebSocket(
          'ws://172.16.150.202/api/swan-cloud-settle-its/zgws/' + str
        )

        that.wsHandler.onopen = function (res) {
          console.log('websocket:open')
          console.log('websocket:', res)
          if (res.currentTarget.readyState === 1) {
            // 连接成功
            that.wsConnected = true
            that.fetchQrCodeUrl()
          } else if (res.currentTarget.readyState === 0) {
            // 尚未建立
          } else if (res.currentTarget.readyState === 2) {
            // 连接正在关闭
          } else if (res.currentTarget.readyState === 3) {
            // 连接已经关闭或者 never connected
            that.wsConnected = false
          }
        }

        that.wsHandler.onmessage = function (evt) {
          console.log('websocket通道消息:', evt.data)
          const msg = evt.data
          if (msg.startsWith('sendText:')) {
            // 发送消息给小助手
            const result = msg.substring(9)
            that.sendMsg({
              type: 'send',
              data: Object.assign(
                that.$store.state.assembleJson.context,
                { order: result }
              )
            })
          } else if (msg.startsWith('sendImage:')) {
            // 发送图片，目前结算系统自己处理
            const imageUrl = msg.substring(10)
            that.loading = true
            setTimeout(() => {
              that.loading = false
            }, 60000)
            that.$http.post('/zg-assistant/image/recognition', {
              imageUrl: 'https://mobile.sxccol.com' + imageUrl,
              formFields: [
                { name: '发运单位', label: 'FYDW' },
                { name: '合同号', label: 'HTH' },
                { name: '填表日期', label: 'TBRQ' },
                { name: '收货单位', label: 'SHDW' },
                { name: '开始发运时间', label: 'KSFYSJ' },
                { name: '结束发运时间', label: 'JSFYSJ' },
                { name: '矿厂', label: 'KC' },
                { name: '等级', label: 'DJ' },
                { name: '煤种', label: 'MZ' },
                { name: '品种', label: 'PZ' },
                { name: '全水分Mt（%）', label: 'QSF' },
                { name: '结算量', label: 'JSL' },
                { name: '拉运量', label: 'LYL' }
              ]
            }, data => {
              that.loading = false
              alert(JSON.stringify(data))
            })
          } else if (msg.startsWith('sendOrder:')) {
            // 接收到小助手发回的指令
            that.loading = false
            const result = msg.substring(10)
            that.handleHelperOrder(result)
          }
        }

        that.wsHandler.onclose = function () {
          console.log('websocket:close')
          that.wsConnected = false
        }

        that.wsHandler.onerror = res => {
          console.log('error:', res)
        }
      }
    },
    refresh () {
      this.isRouterActive = false
      this.$nextTick(() => {
        this.isRouterActive = true
      })
    },
    toScreenFull () {
      if (screenfull.isEnabled) {
        screenfull.toggle()
      }
    },
    toggleHelper () {
      this.showHelper = !this.showHelper
    },
    openMenuDrawer () {
      this.showMenuDrawer = true
    },
    toggleQrCode () {
      this.showQrCode = !this.showQrCode
    },
    fetchQrCodeUrl () {
      this.$http.post('/zg-assistant/qrCode/generate', {
        uuid: uuid
      }, data => {
        this.qrCodeUrl = data
      })
    },
    fetchMenu () {
      this.$http.get('/zg-system/user/menu', {}, data => {
        this.menuArr = data
      })
    },
    generateTime () {
      const date = new Date()
      const year = date.getFullYear() // 年
      const month = date.getMonth() + 1 // 月
      const day = date.getDate() // 日
      const week = date.getDay() // 星期
      const weekArr = [
        '星期日',
        '星期一',
        '星期二',
        '星期三',
        '星期四',
        '星期五',
        '星期六'
      ]
      let hour = date.getHours() // 时
      hour = hour < 10 ? '0' + hour : hour // 如果只有一位，则前面补零
      let minute = date.getMinutes() // 分
      minute = minute < 10 ? '0' + minute : minute // 如果只有一位，则前面补零
      let second = date.getSeconds() // 秒
      second = second < 10 ? '0' + second : second // 如果只有一位，则前面补零
      this.currTime = `${year}年${month}月${day}日 ${weekArr[week]} ${hour}:${minute}:${second}`
    },
    toChangPwd () {
      this.$refs.pwdModal.open()
    },
    toSettings () {
      this.$router.push({ path: '/account/settings' })
    },
    handleLogout (e) {
      Modal.confirm({
        title: '提示',
        content: '您确定要退出系统吗？',
        onOk: () => {
          return this.$store.dispatch('logout').then(() => {
            this.$router.push({ name: 'login' })
          })
        },
        onCancel () {}
      })
    },
    passUserInfo () {
      this.sendMsg({
        type: 'login',
        data: Object.assign(this.$store.state.user, {
          orgCode: '123456',
          token: localStorage.getItem('casToken')
        })
      })
    },
    sendMsg (param) {
      if (param.type === 'send') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
        }, 60000)
      }
      const uuid = localStorage.getItem('uuid')
      param.data = Object.assign({
        // 通道信息
        channelId: uuid + '-' + this.currentUser.username,
        // 消息去向
        showClient: 'PC'
      }, param.data)
			const msg = Object.assign({ source: 'settle' }, param)
      this.$refs.iframe.contentWindow.postMessage(msg, '*')
    }
  }
}
</script>

<style lang="less">
.content{
  border-right:solid 1px #e6e6e6;
}
.mask{
  position:absolute;top:0;left:0;z-index:99999;
  width:100%;height:100vh;background:rgba(0,0,0,0.3);
  font-size:24px;
}
.helper{
  position:absolute;
  z-index:999;
  bottom:80px;
  right:60px;
  width:48px;
  height:48px;
  border-radius:50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor:pointer;
  background:#999;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: box-shadow 0.2s;
  &:hover{
    box-shadow: 0 4px 16px rgba(24, 144, 255, 0.25);
    background: #40a9ff;
  }
}
.btn{
  width:32px;
  height:32px;
  border-radius: 50%;
  background: transparent;
  cursor:pointer;
  &:hover{
    background:#fff;
    .fa{
      color:#333;
    }
  }
}
.zg-iframe{
  height:calc(100vh - 80px);
  display:block;
  width:100%;
  border:0px;
  margin:0;
}
</style>
